//
//  RankListView.swift
//  MM2
//
//  Created by 李成明 on 2022/1/7.
//

import UIKit
import MJRefresh

private class RequestModel: BaseModel {
    var result: Bool = false
    var errorMsg: String = ""
    var data: RequestDataModel?
}

private class RequestDataModel: BaseModel {
    var rankList: [RankListModel] = []
}

private class TabbleHeaderView: UIView {
    
    static let viewHeight = 40.0
    
    override init(frame: CGRect) {
        super.init(frame: frame)
        backgroundColor = .clear
        layer.masksToBounds = true
        layer.cornerRadius = 10
        
        addSubview(bgView)
        addSubview(content)
        content.snp.makeConstraints { make in
            make.edges.equalTo(self)
        }
        bgView.snp.makeConstraints { $0.edges.equalTo(self) }
    }
    
    required init?(coder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }
    
    private lazy var content: UILabel = {
        let view = UILabel()
        view.font = .systemFont(ofSize: 20)
        view.text = "   用户名    排名    图片/头像    颜值分数"
        return view
    }()
    
    private lazy var bgView: UIImageView = {
        let bgView = UIImageView(image: UIImage(named: "rank_header_bg_img"))
        bgView.alpha = 0.5
        return bgView
    }()
}

class RankListView: UIView {
    
    override init(frame: CGRect) {
        super.init(frame: frame)
        NotificationCenter.default.addObserver(self, selector: #selector(tableViewHeaderAction), name: Notification.Name(notifiRankChange), object: nil)
        
        setupUI()
    }
    
    required init?(coder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }
    
    deinit {
        NotificationCenter.default.removeObserver(self)
    }
    
    private var dataSource: [RankListModel] = []
    
    private var pageNum = 1
    private var fightClosure: ((RankListModel) -> Void)?
    
    private lazy var tableView: UITableView = {
        let view = UITableView.init(frame: CGRect.zero, style: .plain)
        view.showsVerticalScrollIndicator = false
        view.showsHorizontalScrollIndicator = false
        view.backgroundColor = .clear
        view.separatorStyle = .none
        view.delegate = self
        view.dataSource = self
        
        let header = MJRefreshNormalHeader.init(refreshingTarget: self, refreshingAction: #selector(tableViewHeaderAction))
        let footer = MJRefreshBackNormalFooter.init(refreshingTarget: self, refreshingAction: #selector(tableViewFooterAction))
        header.setTitle("", for: .pulling)
        header.setTitle("", for: .refreshing)
        header.setTitle("", for: .idle)
        header.lastUpdatedTimeLabel?.isHidden = true
        footer.setTitle("", for: .idle)
        footer.setTitle("", for: .pulling)
        footer.setTitle("", for: .refreshing)
        view.mj_header = header
        view.mj_footer = footer
        
        let footerView = UIView.init(frame: CGRect(x: 0, y: 0, width: kScreenWidth, height: 50))
        view.tableFooterView = footerView
        
        view.register(RankListImageCell.self, forCellReuseIdentifier: "RankListImageCell")
        view.register(RankListNormalCell.self, forCellReuseIdentifier: "RankListNormalCell")
        return view
    }()
}

extension RankListView: UITableViewDelegate, UITableViewDataSource {
    func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
        return dataSource.count
    }
    
    func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
        if indexPath.row < 10 {
            let cell = tableView.dequeueReusableCell(withIdentifier: "RankListImageCell", for: indexPath)
            if let cell = cell as? RankListImageCell {
                cell.model = dataSource[safe: indexPath.row]
            }
            return cell
        } else {
            let cell = tableView.dequeueReusableCell(withIdentifier: "RankListNormalCell", for: indexPath)
            if let cell = cell as? RankListNormalCell {
                cell.model = dataSource[safe: indexPath.row]
            }
            return cell
        }
    }
    
    func tableView(_ tableView: UITableView, heightForRowAt indexPath: IndexPath) -> CGFloat {
        if indexPath.row < 10 {
            return RankListImageCell.cellHeight
        } else {
            return RankListNormalCell.cellHeight
        }
    }
    
    func tableView(_ tableView: UITableView, viewForHeaderInSection section: Int) -> UIView? {
        return TabbleHeaderView(frame: CGRect(x: 0.0, y: 0, width: kScreenWidth, height: TabbleHeaderView.viewHeight))
    }
    
    func tableView(_ tableView: UITableView, heightForHeaderInSection section: Int) -> CGFloat {
        return TabbleHeaderView.viewHeight
    }
    
    func tableView(_ tableView: UITableView, canEditRowAt indexPath: IndexPath) -> Bool {
        return true
    }
    
    func tableView(_ tableView: UITableView, trailingSwipeActionsConfigurationForRowAt indexPath: IndexPath) -> UISwipeActionsConfiguration? {
        let action = UIContextualAction.init(style: .normal, title: nil) { [weak self] action, view, closure in
            tableView.setEditing(false, animated: true)
            self?.fightClickAction(indexPath: indexPath)
            closure(true)
        }
        action.image = UIImage(named: "rank_fight_icon")
        action.backgroundColor = .initWithRGB(209, 225, 234)
        
        let actions = UISwipeActionsConfiguration.init(actions: [action])
        actions.performsFirstActionWithFullSwipe = false
        return actions
    }
}

extension RankListView {
    private func setupUI() {
        addsubViews([tableView])
        tableView.snp.makeConstraints { make in
            make.edges.equalTo(self)
        }
    }
}

extension RankListView {
    private func fightClickAction(indexPath: IndexPath) {
        guard let model = dataSource[safe: indexPath.row] else { return }
        fightClosure?(model)
    }
    
    @discardableResult
    func fight(_ closure: ((RankListModel) -> Void)?) -> RankListView{
        fightClosure = closure
        return self
    }
    
    @objc private func tableViewHeaderAction() {
        self.pageNum = 1
        self.dataSource.removeAll()
        self.request()
    }
    
    @objc private func tableViewFooterAction() {
        self.pageNum += 1
        self.request()
    }
}

extension RankListView {
    func request() {
        MoyaNetwork.request(target: BaseApi.rankList(page: pageNum)) { json, jsonStr in
            guard let requestModel = RequestModel.deserialize(from: jsonStr), let array = requestModel.data?.rankList else { return }
            self.dataSource += array
            self.dataSource =  self.dataSource.sorted(by: >)
            for (index, item) in self.dataSource.enumerated() {
                item.rankNum = index + 1
            }
            self.tableView.reloadData()
            self.tableView.mj_header?.endRefreshing()
            self.tableView.mj_footer?.endRefreshing()
        }

    }
}
